package controllers

import (
	"day20/cache"
	"day20/models"
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type ProductController struct {
	beego.Controller
}

type Res struct {
	Code    int         `json:"code"`
	Data    interface{} `json:"data"`
	Message string      `json:"message"`
}

func (c *ProductController) List() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	keyword := c.GetString("keyword")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")
	var product models.Product
	var list []*models.Product

	key := fmt.Sprintf("product_list_%s_%d", keyword, page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		list, _ = product.List(keyword, page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*24)
		}
	} else {
		fmt.Println("获取成功")
		json.Unmarshal([]byte(cacheData), &list)
	}

	c.Data["json"] = Res{
		Code:    200,
		Data:    list,
		Message: "查询成功",
	}
	c.ServeJSON()
	return
}

func (c *ProductController) Update() {
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetFloat("price")
	description := c.GetString("description")
	stock, _ := c.GetInt("stock")

	product := models.Product{
		Name:        name,
		Price:       price,
		Description: description,
		Stock:       stock,
	}
	product.ID = uint(id)
	if err := product.GetProBy(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	if err := product.Update(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("product_update_%d", product.ID)
	jsonData, _ := json.Marshal(product)
	cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour*24)

	c.Data["json"] = Res{
		Code:    200,
		Data:    product,
		Message: "修改成功",
	}
	c.ServeJSON()
	return
}

func (c *ProductController) Del() {

	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")

	id, _ := c.GetInt("id")
	var product models.Product
	product.ID = uint(id)

	if err := product.GetProBy(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
	}

	if err := product.Del(); err != nil {
		c.Data["json"] = Res{
			Code:    500,
			Data:    nil,
			Message: "系统错误",
		}
	}

	key := fmt.Sprintf("product_del_%d", product.ID)
	cache.Rdb.Del(cache.Ctx, key)

	c.Data["json"] = Res{
		Code:    200,
		Data:    product,
		Message: "删除成功",
	}
	c.ServeJSON()
	return
}
